package com.taoge.p4.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taoge.p4.common.constants.GlobalConstants;
import com.taoge.p4.common.entity.UserBase;
import com.taoge.p4.common.entity.UserInfo;
import com.taoge.p4.common.errorCode.SecurityErrorCode;
import com.taoge.p4.common.exception.BusinessException;
import com.taoge.p4.common.mapper.UserBaseMapper;
import com.taoge.p4.common.mapper.UserInfoMapper;
import com.taoge.p4.common.params.ApiRegisterParam;
import com.taoge.p4.common.params.LoginParam;
import com.taoge.p4.common.service.UserBaseService;
import com.taoge.p4.common.utils.PasswordUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@RequiredArgsConstructor
public class UserBaseServiceImpl extends ServiceImpl<UserBaseMapper, UserBase> implements UserBaseService {
    private final UserInfoMapper userInfoMapper;

    private final UserBaseMapper userBaseMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(ApiRegisterParam param) {
        UserBase exist = userBaseMapper.selectOne(new LambdaQueryWrapper<UserBase>().eq(UserBase::getUsername, param.getUsername()));
        if (exist != null) {
            throw new BusinessException(SecurityErrorCode.USERNAME_EXISTS_ERROR, param.getUsername(), exist.getCreateTime());
        }

        UserBase userBase = new UserBase();
        String passwordAndSalt = PasswordUtil.encryptionPassword(param.getPassword());
        String[] split = passwordAndSalt.split("-");
        userBase.setPassword(param.getMobile());
        userBase.setUsername(param.getUsername());
        userBase.setPassword(split[0]);
        userBase.setSalt(split[1]);
        userBase.setStatus(GlobalConstants.USER_STATUS_NORMAL);
        userBase.setRegisterTime(new Date());
        userBase.setMobile(param.getMobile());
        userBaseMapper.insert(userBase);

        UserInfo info = new UserInfo();
        info.setNickname("昵称" + System.currentTimeMillis());
        info.setGender(param.getGender());
        info.setBirthday(param.getBirthday());
        info.setAvatar(param.getAvatar());
        info.setCreateTime(new Date());
        info.setUpdateTime(new Date());
        userInfoMapper.insert(info);
    }

    @Override
    public UserBase login(LoginParam param) {
        UserBase userBase = userBaseMapper.selectOne(new LambdaQueryWrapper<UserBase>().eq(UserBase::getUsername, param.getUserName()));
        if (userBase == null) {
            throw new BusinessException(SecurityErrorCode.PASSWORD_ERROR);
        }

        // 校验密码是否一致
        String password = PasswordUtil.encryptionPassword(param.getPassword(), userBase.getSalt());

        // 密码不一致，抛异常
        if (!password.equals(userBase.getPassword())) {
            throw new BusinessException(SecurityErrorCode.PASSWORD_ERROR);
        }

        userBaseMapper.update(null, new LambdaUpdateWrapper<UserBase>()
                .set(UserBase::getLastLoginTime, new
                        Date())
                .eq(UserBase::getId, userBase.getId())  // 确保只更新当前用户的记录
        );
        return userBase;
    }
}
